<template>
  <div class="receipt-info">
    <SectionTitle title="关联到账流水" style="margin-bottom: 22px;">
      <div v-if="!showMobilePage" class="data-container">
        <dataDisplay :data-list="dataList"/>
      </div>
      <div v-if="isCreate || (processStatus !== 3 && isCurrentVersion && setEvents && isCurrentUserApproval)" class="options-btn-group">
        <PlainCreateBtn @click="openReleatedFinance">关联流水</PlainCreateBtn>
      </div>
    </SectionTitle>
    <dataDisplay v-if="showMobilePage" :data-list="dataList" style="margin-bottom: 12px"/>
    <u-table
      v-if="tableData.length > 0"
      ref="receiptTableRef"
      :data="tableList"
      :row-class-name="tableRowClassName"
      :row-height="49"
      :border="true"
      beautify-table
      header-drag-style
      use-virtual
      class="fb-table"
      element-loading-text="加载中..."
      empty-text="暂无数据"
      header-cell-class-name="order-data-header-cell"
      fit
      hightlight-current-row>
      <u-table-column align="left" label="到账日期" min-width="120" prop="arrivalTime" sortable>
        <template slot-scope="scope">
          {{ scope.row.arrivalTime | standardFormat('YYYY/MM/DD') }}
        </template>
      </u-table-column>
      <u-table-column align="left" label="交易单号" min-width="120">
        <template slot-scope="scope">
          <el-tooltip v-if="scope.row.transactionNumber" class="item" placement="top" effect="dark">
            <div slot="content" style="max-width: 200px;">{{ scope.row.transactionNumber }}</div>
            <div class="ellipsis pointer" style="color:#406eff;" @click="btnCheck(scope)">{{ scope.row.transactionNumber }}</div>
          </el-tooltip>
          <div v-else>--</div>
        </template>
      </u-table-column>
      <u-table-column align="right" label="收入金额(元)" min-width="130" prop="incomeAmount" sortable>
        <template slot-scope="scope">
          <PriceColumn :real-val="scope.row.incomeAmount" :price="scope.row.incomeAmount / 100" />
        </template>
      </u-table-column>
      <u-table-column align="right" label="可核销金额(元)" min-width="140" prop="unWriteOffAmount" sortable>
        <template slot-scope="scope">
          <PriceColumn :real-val="scope.row.unWriteOffAmount" :price="scope.row.unWriteOffAmount / 100" />
        </template>
      </u-table-column>
      <u-table-column align="left" label="付款人名称" min-width="120">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.payName" :class="{'red-color': scope.row.payName !== taxPayer}"/>
        </template>
      </u-table-column>
      <u-table-column align="left" label="已关联审批" min-width="100">
        <template slot-scope="scope">
          <div v-if="!scope.row.invoiceApplyList">0</div>
          <el-tooltip
            v-if="scope.row.invoiceApplyList && scope.row.invoiceApplyList.length > 0"
            placement="top"
            effect="light"
            popper-class="link-approval-tip">
            <div slot="content" class="apply-content">
              <el-table
                :data="scope.row.invoiceApplyList"
                style="width: 100%"
                max-height="200px">
                <el-table-column label="审批单号" min-width="180">
                  <template slot-scope="scope">
                    <div class="light-word" @click="toApplyDetail(scope.row)">{{ scope.row.sn }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="含税金额(元)" align="right" min-width="120">
                  <template slot-scope="scope">
                    <PriceColumn :real-val="scope.row.amount" :price="scope.row.amount" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <span class="red-word">{{ scope.row.invoiceApplyList.length }}</span>
          </el-tooltip>
        </template>
      </u-table-column>
      <u-table-column align="left" label="付款账号" min-width="80">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.payNumber"/>
        </template>
      </u-table-column>
      <u-table-column align="left" label="备注" min-width="80">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.remark"/>
        </template>
      </u-table-column>
      <u-table-column align="left" label="所属部门" min-width="120">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.departmentName"/>
        </template>
      </u-table-column>
      <u-table-column align="left" label="创建人" min-width="80">
        <template slot-scope="scope">
          <CheckUserInfo v-if="scope.row.createName" :label="scope.row.createName" :user-id="scope.row.creatorId" />
          <div v-else>--</div>
        </template>
      </u-table-column>
      <u-table-column align="left" label="创建时间" min-width="120" prop="createTime" sortable>
        <template slot-scope="scope">
          <ToolTip :content="scope.row.createTime | standardFormat('YYYY/MM/DD HH:mm')"/>
        </template>
      </u-table-column>
      <u-table-column v-if="isCreate || (processStatus !== 3 && isCurrentVersion && setEvents && isCurrentUserApproval)" align="left" width="110" label="操作" fixed="right">
        <template slot-scope="scope">
          <div style="display:flex;">
            <div class="button-text" @click="handleDelete(scope.row)">删除</div>
          </div>
        </template>
      </u-table-column>
    </u-table>
    <EmptyPlaceholder v-else slot="empty" empty-text="暂无数据" mode="border" style="padding:12px 0 18px 0"/>
    <div style="text-align: right;">
      <el-pagination
        v-show="tableData.length > 10"
        :current-page="page"
        :page-size="perPage"
        :total="tableData.length"
        :page-sizes="[10, 20, 50, 100, 250, 500]"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <ReleatedFinance
      v-if="!resetFlag"
      ref="releatedFinance"
      :visible.sync="showRelatedFinance"
      :issue-id="issueId"
      @confirm="selectFinance"
    />
  </div>
</template>

<script>
import SectionTitle from '@/components/Title';
import { standardFormat } from '@/filters/date';
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import ReleatedFinance from '@/components/Finance/releatedFinance';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import icon_17 from '@/assets/dataDisplay/icon_17.png';
import { mapState } from 'vuex';
import { showModal } from '@/utils/message';

export default {
  components: { SectionTitle, ReleatedFinance, dataDisplay, EmptyPlaceholder },
  filters: { standardFormat },
  mixins: [tableSelections, TableAdaptive],
  props: {
    tableData: {
      type: Array,
      default() {
        return [];
      }
    },
    setEvents: {
      type: Boolean,
      default: false
    },
    isCurrentUserApproval: {
      type: Boolean,
      default: false
    },
    isCurrentVersion: {
      type: Boolean,
      default: false
    },
    isCreate: {
      type: Boolean,
      default: false
    },
    issueId: { // 开票申请id
      type: Number | String,
      default: null
    },
    processStatus: { // 审批流程状态
      type: Number,
      default: null
    },
    taxPayer: { // 纳税人名称
      type: String,
      default: ''
    },
    applicationInfo: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      showRelatedFinance: false,
      page: 1,
      perPage: 10,
      resetFlag: false,
      tableRefName: 'receiptTableRef', // 表格的ref名称
      idKey: 'id' // 唯一表示字段
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    tableList() {
      return this.tableData.slice((this.page - 1) * this.perPage, this.page * this.perPage);
    },
    dataList() {
      if (this.tableData.length === 0) {
        return [
          { label: '收入金额', data: 0, icon: icon_17, width: '200px' },
          { label: '可核销金额', data: 0, icon: icon_17, width: '200px' }
        ];
      }
      let incomeAmount = this.tableData.reduce((pre, next) => {
        return Number(pre) + Number(next.incomeAmount);
      }, 0);
      incomeAmount = (incomeAmount / 100).toFixed(2);
      let unWriteOffAmount = this.tableData.reduce((pre, next) => {
        return Number(pre) + Number(next.unWriteOffAmount);
      }, 0);
      unWriteOffAmount = (unWriteOffAmount / 100).toFixed(2);
      return [
        { label: '收入金额', data: incomeAmount, icon: icon_17, width: '200px' },
        { label: '可核销金额', data: unWriteOffAmount, icon: icon_17, width: '200px' }
      ];
    }
  },
  methods: {
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.$emit('addSort', { sortName: this.sortName, sortType: this.sortType });
    },
    selectFinance(val) {
      /**
        纳税人为个人时且是否到账(isArrival)为是：
        如果关联到账流水的付款人有和纳税人不一样则弹窗提示
       */
      // taxpayerType  0:公司  1:个人
      if (this.applicationInfo.taxpayerType === 1 && this.applicationInfo.taxpayer && val && val.length) {
        const isSame = val.every(i => {
          return i.payName === this.applicationInfo.taxpayer;
        });
        if (!isSame) {
          showModal('请注意你填写的纳税人名称与付款人名称不一致，是否要继续填写?', '', {
            confirmButtonText: '继续填写',
            cancelButtonText: '暂不填写',
            type: 'warning',
            showClose: false,
            center: true,
            iconClass: 'charge-icon',
            customClass: 'del-message del-message-cancel'
          }, true).then(() => {
            this.$emit('selectFinance', val);
            this.page = 1;
          }).catch(() => {
            this.resetFlag = true;
            setTimeout(() => {
              this.resetFlag = false;
            }, 100);
          });
          return;
        }
      } else if (!this.applicationInfo.taxpayer && val && val.length) {
        // 如果先关联到账流水，则填充第一条类型为公司的付款人到纳税人信息
        let company = null;
        for (let i = 0; i < val.length; i++) {
          if (val[i].clientType === 0) {
            company = val[i];
            break;
          }
        }
        if (company) {
          this.$emit('fillTaxpayerInfo', company);
        }
      }
      this.$emit('selectFinance', val);
      this.page = 1;
    },
    handleDelete(row) {
      this.$emit('handleDelete', row.id);
    },
    handleSizeChange(val) {
      this.perPage = val;
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
    },
    toApplyDetail(row) {
      const routerData = {
        name: 'issueInvoiceDetail',
        query: {
          issueId: row.invoiceApplyId,
          processId: row.workFlowId
        }
      };
      const url = this.$router.resolve(routerData);
      window.open(url.href, '_blank');
    },
    getIds() {
      return this.tableData.map(item => item.id).join();
    },
    btnCheck(scope) {
      const routerData = {
        name: 'chargeOffDetail',
        params: { chargeOffId: scope.row.id }
      };
      const url = this.$router.resolve(routerData);
      window.open(url.href, '_blank');
    },
    openReleatedFinance() {
      this.showRelatedFinance = true;
      const params = { clientName: '' };
      let exactForClientName = 0;
      // taxpayerType 0:公司 1:个人
      if (this.applicationInfo && this.applicationInfo.taxpayer && this.applicationInfo.taxpayerType === 0) {
        params.clientName = this.applicationInfo.taxpayer;
        exactForClientName = 1;
      }
      this.$refs['releatedFinance'].init(params, exactForClientName);
      if (this.tableData.length > 0) {
        this.$refs['releatedFinance'].initSelectData(this.tableData);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.receipt-info {
  margin-top: 16px;
}
.data-container {
  margin-left: 10px;
}
.options-btn-group {
  position: absolute;
  right: 0;
}
.apply-content {
  width: 300px;
}
.light-word {
  color: #406eff;
  cursor: pointer;
}
.red-word {
  color: #FF4E5F;
  cursor: pointer;
}
.red-color {
  color: #FF4E5F;
}
</style>
<style lang="scss">
.link-approval-tip {
  padding: 12px 16px !important;
  border: none !important;
  background: white !important;
	box-shadow: 1px 1px 10px 3px #D3D3D6;
  .popper__arrow, .popper__arrow:after {
    border-top-color: white !important;
    border-bottom-color: white !important;
  }
}
</style>
